<?php
namespace Member\Controller;
use Common\Controller\BaseController;

class MemberController extends BaseController
{
    protected $userModel = '';

    function _initialize()
    {
        //检测是否登录
        $this->check_login();
    }

    /**
     **开始抽奖
     **/
    public function draw()
    {
//		if(IS_POST){
        //时间是否在范围之内
        $now_time = time();
        if ($now_time < strtotime(C(START_TIME))) {
            $this->rtnResult(3, '活动还未开始，请耐心等待');
        }
        if ($now_time > strtotime(C(END_TIME))) {
            $this->rtnResult(4, '活动已结束');
        }


        $up_time = S('clean_time');
        if (empty($up_time)) {
            //清空
            $chance = M('Chance')-> where('pk_id in(1,2,3,4,5)') ->setField('counter', '0');

            S('clean_time', date('Y-m-d'));
        } else {
            //判断时间

            $nowdate = date('Y-m-d');
            if ($up_time != $nowdate) {
                $chance = M('Chance')-> where('pk_id in(1,2,3,4,5)') ->setField('counter', 0);
                S('clean_time', date('Y-m-d'));
            }
        }


        //今日免费参与次数
//			$play = M('play');
//			$nowdate = date('Y-m-d');
//			$time = $play -> where("fk_user_id = {$_SESSION['userid']} AND create_time LIKE '$nowdate%'")->limit(3)->count();

        //可参与次数
        $availableNum = $this->getPlayNumber();
        if ($availableNum == 0) {
            $play_times = M('User')->where('pk_id=%d', $_SESSION['userid'])->getField('play_times');
            if ($play_times <= 0) {
                // $this->rtnResult(1, '您已经没有次数啦');
                 // header("Location:{:C('APP_URL')}");
                header("Location:http://zsh.nidjia.com");
                exit();
                // header('location:'.U('Home/Index/index'));
            }
        }
        //------------------------------开始抽奖-------------------------------------
        $scratch_prize = M('chance');
        $prizeList = $scratch_prize->where('number > 0 AND chance > 0 AND supply >= counter')->field('pk_id,worth,keju,name,chance,score,win_show,prize_name,number,counter,supply')->select();

        $prizeInfo = $this->luckDraw($prizeList);//抽奖

        //调用抽奖结果
        $result = $this->get_luckDraw_result($prizeInfo['win_show']);

        //-------------------------------抽奖结束----------------------------------------
        //次数
        $User = M('User');
        $User->startTrans();
//        if ($availableNum == 0) {
//            $result = $User->where('pk_id= %d', $_SESSION['userid'])->setDec('play_times', 1);
//            !$result && $this->rtnResult(1, '出错啦', $User);
//        }

        //判断是否中奖
        if (!$prizeInfo['pk_id']) {
            //没有中奖，返回首页继续游戏
//                $this -> rtnResult(2,'您没有中奖');
        } else {
            //奖品数量减一
            $scratch_prize->where('pk_id=%d', $prizeInfo['pk_id'])->setDec('number', 1);
            $scratch_prize->where('pk_id=%d', $prizeInfo['pk_id'])->setInc('counter', 1);
            $_SESSION['fk_chance_id'] = $prizeInfo['pk_id'];
            $_SESSION['prize_name'] = $prizeInfo['prize_name'];
        }

        $data['fk_user_id'] = $_SESSION['userid'];
        $data['prize'] = $prizeInfo['name'];
        $data['fk_prize_id'] = $_SESSION['prize_id'];
        $data['fk_chance_id'] = $prizeInfo['pk_id'];
        $data['prize_name'] = $prizeInfo['prize_name'];
        $logid = M('play')->add($data);
        !$logid && $this->rtnResult(2, '保存失败，请重试!', $User);

        //抽奖成功，页面获取结果
        $this->data['prize_name'] = $prizeInfo['prize_name'];
        $this->data['worth'] = $prizeInfo['worth'];
        $this->data['prize_id'] = $prizeInfo['pk_id'];
        $this->data['chance_name'] = $prizeInfo['name'];
        $this->data['result'] = $result;
        $this->data['cj_times'] = $availableNum - 1;
        $data = $this->data;
        unset($this->data);
        return $data;
//        $this->rtnResult(0, '抽奖成功!', $User);
//		}
//        else{
//			//可参与的次数
//			$play_log = M('play');
//			$num = $play_log -> where("fk_user_id={$_SESSION['userid']}") ->limit(3) ->count();
//			$availableNum = C('FREE_NUM') - $num;
//			if($availableNum <=0) $availableNum = 0;
//
//			//获取用户信息
//			$info = M('User') -> where('pk_id=%d',$_SESSION['userid']) -> find();
//			$info['play_times'] = $availableNum;
//			$data['info'] = $info;
//			$this -> showView($data,'./public/draw.html');
//		}
    }

    public function advert(){
        $this -> showView('','./Public/advert.html');
    }

    /**
     * 获取抽奖结果
     */
    function get_luckDraw_result($win_show)
    {
        $str = $win_show;
        $arr = explode('+', $str);
        foreach ($arr as $ar) {
            list($count, $num) = explode('(', $ar);
            list($num) = explode(')', $num);
            if (stripos($num, '|') !== false) {
                $tor = explode('|', $num);
                $key = @array_search($result[0], $tor);
                if ($key !== false) {
                    unset($tor[$key]);
                }
                shuffle($tor);
                $rot = $tor;
                shuffle($rot);
                $tor = array_merge($tor, $rot);
                $dian = array_slice($tor, 0, $count - 1);
                $dian[] = $tor[rand(0, count($tor) - 1)];
                $dian = implode('', $dian);
                $result .= $dian;
            } else {
                $tor = explode(',', $num);
                if (count($tor) !== 1) {
                    shuffle($tor);
                }
                $dian = $tor[0];
                $result .= str_repeat($dian, $count);
            }
            $result = str_shuffle($result);
        }
        return str_split($result, 1);
    }

    /**
     * 抽奖
     * Enter description here ...
     * @param unknown_type $prizeList 奖品列表（二维）
     * @param unknown_type $is_must 是否100%中奖，1是，2否（会生成一个空奖）
     * return array 奖品（一维）
     */
    function luckDraw($prizeList, $is_must = false)
    {
        //遍历数组，将中奖概率转换成数值
        foreach ($prizeList as $v) {
            $pbyCount += $v['chance'] * 1000; //所有奖品加起来的中奖概率
            $award[] = array('pk_id' => $v['pk_id'], 'keju' => $v['keju'], 'name' => $v['name'], 'score' => $v['score'], 'win_show' => $v['win_show'], 'probability' => $pbyCount, 'prize_name' => $v['prize_name'] ,'worth' => $v['worth']);
        }

        //概率不足100%时，以'谢谢参与补足100%'
        if (empty($is_must)) {
            $noWin = 100000 - $pbyCount;
            if ($noWin > 0) {
//                $award[] = array('pk_id'=>0,'name' => '谢谢参与','probability'=>100000);
                $award[] = array('pk_id' => 0, 'keju' => '谢谢参与', 'name' => '谢谢参与', 'score' => 0, 'win_show' => '6(1|2|3|5|6)', 'prize_name' => '谢谢参与', 'probability' => 100000);
            }
        }

        //返回给客户端的奖品名称
        $rand = rand(1, 100000);
        foreach ($award as $key => $value) {
            if ($rand >= 1 + $award[$key - 1]['probability'] && $rand <= $award[$key]['probability']) {
                return $award[$key];
            }
        }
    }

    //------------------------------------用户收下奖品------------------------------------------
    public function getprize()
    {
        if (IS_POST) {


            //验证
            $name = I('name');
            $phone = I('phone');
            $address = I('address');
            $shop = I('shop');
            $prize_id = I('prize_id');
            if (!$phone) {
                $this->rtnResult(1, '无效的请求');
            }
            //手机格式验证
            if (preg_match("/^1[34578]\d{9}$/", $phone) === false) {
                $this->rtnResult(1, '手机号不是11位，请重新输入');
            }
            //是否中奖
            if ($prize_id != $_SESSION['fk_chance_id'] || !$_SESSION['fk_chance_id']) {
                $this->rtnResult(2, '非法操作');
            }
            //保存用户信息
            $User = M('User');
            $User->startTrans();
            $uData['name'] = $name;
            $uData['phone'] = $phone;
            $uData['address'] = $address;
            $uData['shop'] = $shop;
            $result = $User->where('pk_id=%d', $_SESSION['userid'])->save($uData);
            $result === false && $this->rtnResult(1, '系统错误', $User);

            //添加奖品到数据表
            $Chance = M('Chance');
            $info = $Chance->where('pk_id=%d', $_SESSION['fk_chance_id'])->field('pk_id,worth,prize_name,number')->find();
            $data['fk_user_id'] = $_SESSION['userid'];
            $data['prize_name'] = $info['prize_name'];
            $data['worth'] = $info['worth'];
            $data['name'] = $name;
            $data['phone'] = $phone;
            $data['address'] = $address;
            $data['shop'] = $shop;
            $data['fk_chance_id'] = $info['pk_id'];
            $logid = M('myprize')->add($data);
            !$logid && $this->rtnResult(2, '保存失败，请重试!', $User);


            //每收下一件，商品表相对应的商品数量减1
            // $prizeData = $Chance->where('pk_id = %d', $_SESSION['fk_chance_id'])->setDec('number', 1);
            // !$prizeData && $this->rtnResult(3, '保存失败，请重试！', $User);
            unset($_SESSION['fk_chance_id']);

            //清除我的奖品缓存
            S('my_prize_list_'.$_SESSION['userid'],null);

            $this->rtnResult(0, '收下成功！', $User);

        }

    }
    public function gift(){

        $this -> showView('','./Public/gift.html');
    }
}

























































